<?php
declare (strict_types=1);

namespace app\admin\controller;

use think\exception\ValidateException;

class Index extends Base
{
    protected $noLoginAction = ['*'];

    public function index()
    {
        return json(['name' => 'thinkphp', 'status' => '1']);
    }

    public function test()
    {
        if ($this->request->isPost()) {
            $data = input('post.params');
            $data = array_map(function ($v) {
                return $v['field'] ? ($v['field'] . '=' . $v['value']) : null;
            }, $data);
            $url = input('post.url');
            $curl = curl_init($url);
            curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER => 1, CURLOPT_POST => 1, CURLOPT_POSTFIELDS => join('&', array_filter($data))]);
            $res = curl_exec($curl);
            $code = curl_errno($curl);
            $msg = curl_error($curl);
            curl_close($curl);

            dump($code, $res, $msg, curl_strerror($code));
            exit;
        }
        return $this->view->fetch();
    }

    /**
     * login #
     *
     * @auth kouweihong
     * @date 2020/11/24
     */
    public function login()
    {
        $this->request->isPost() || $this->error('非法操作');
        $username = input('post.username');
        $password = input('post.password');
        (!$username || !$password) && $this->error('账户密码错误');

        //查询用户信息
        $password = md5(md5($password));
        $user = \app\common\model\User::getInfoByWhere(['user_type' => \app\common\model\User::USER_TYPE_1, 'username' => $username, 'password' => $password]);
        $user->isEmpty() && $this->error('账户密码不存在');
        $user->token = \Random::uuid();

        //更新用户信息
        $data = [
            'login_ip' => $this->request->ip(),
            'login_time' => time(),
            'login_token' => $user->token,
            'login_token_expire' => time() + 7200,
        ];
        $res = $user->save($data);
        $res === false && $this->error('登录失败');

        $this->success($user->toArray());
    }

    /**
     * register #
     *
     * @auth kouweihong
     * @date 2020/11/24
     */
    public function register()
    {
        $this->request->isPost() || $this->error('非法操作');
        $params = input('post.');
        (!$params) && $this->error('提交参数为空');

        //查询用户是否存在
        try {
            validate(\app\common\validate\User::class)->check($params);

            //保存数据
            $params['nickname'] = $params['username'];
            $params['password'] = md5(md5($params['password']));
            $params['user_type'] = 1;
            $params['register_ip'] = $this->request->ip();
            $user = \app\common\model\User::create($params);
            $user->isEmpty() && $this->error('注册失败');

            $this->success('注册成功');
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
    }
}
